package api.email;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Properties;

public class SendEmail {

    //生成网页内容
    public String createEmailContent(ArrayList<EmailContentBean> list) {
        if (list == null || list.size() <= 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        sb.append("<!doctype html>\n" +
                "<html lang=\"en\">\n" +
                "\n" +
                " <head>\n" +
                "  <meta charset=\"UTF-8\">\n" +
                "  <meta name=\"Generator\" content=\"EditPlus®\">\n" +
                "  <meta name=\"Author\" content=\"\">\n" +
                "  <meta name=\"Keywords\" content=\"\">\n" +
                "  <meta name=\"Description\" content=\"\">\n" +
                "  <script type=\"text/javascript\">\n" +
                " window.onload=function(){\n" +
                " var tfrow = document.getElementById('tfhover').rows.length;\n" +
                " var tbRow=[];\n" +
                " for (var i=1;i<tfrow;i++) {\n" +
                " tbRow[i]=document.getElementById('tfhover').rows[i];\n" +
                " tbRow[i].onmouseover = function(){\n" +
                " this.style.backgroundColor = '#ffffff';\n" +
                " };\n" +
                " tbRow[i].onmouseout = function() {\n" +
                " this.style.backgroundColor = '#d4e3e5';\n" +
                " };\n" +
                " }\n" +
                "};\n" +
                "  </script>\n" +
                "  <style type=\"text/css\">\n" +
                "table.tftable {font-size:12px;color:#333333;width:100%;border-width: 1px;border-color: #729ea5;border-collapse: collapse;}\n" +
                "table.tftable th {font-size:12px;background-color:#acc8cc;border-width: 1px;padding: 8px;border-style: solid;border-color: #729ea5;text-align:left;}\n" +
                "table.tftable tr {background-color:#d4e3e5;}\n" +
                "table.tftable td {font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: #729ea5;}" +
                ".resonse {height: 6em;overflow: scroll;width: 300px;}\n" +
                ".parmas {width: 200px;}" +
                "</style>\n" +
                "  <title>Document</title>\n" +
                " </head>\n" +
                " <body>\n" +
                "  <table id=\"tfhover\" class=\"tftable\" border=\"1\">\n" +
                "<tr><th>序号</th><th>接口名描述</th><th>用例描述</th><th width=30%>出错api地址</th><th>参数</th><th>返回信息</th><th>错误时间</th></tr>");
        EmailContentBean emailContentBean = null;
        for (int i = 0, k = list.size(); i < k; i++) {
            emailContentBean = list.get(i);
            sb.append(
                    "<tr><td>" + i + "</td>" +
                            "<td> <div class=name>" + emailContentBean.getApiName() + "</div></td>" +
                            "<td><div class=name>" + emailContentBean.getDescription() + "</div></td>" +
                            "<td><div class=addr>" + emailContentBean.getErrarAPIaddress() + "</div></td>" +
                            "<td ><div class=parmas>" + emailContentBean.getParams() + "</div></td>" +
                            "<td><div class=resonse>" + emailContentBean.getResponse() + "</div></td>" +
                            "<td> <div class=time>" + emailContentBean.getTime() + "</div></td>");
        }
        sb.append("</table>\n" +
                " </body>\n" +
                "</html>");
        return sb.toString();
    }

    /**
     * 发送邮箱账号  xxx@xxx.com形式
     * 发送邮件密码
     * stmp服务器地址
     * smtp服务器端口
     * 发件人地址
     *
     * @param tos     收件人地址
     * @param title   标题
     * @param content 内容
     */
    public void sendmessage(String[] tos, String title, String content) {
        try {
            //创建session实例
            Session session = initProperties();
            MimeMessage message = new MimeMessage(session);
            session.setDebug(true);

            //设置from发件人邮箱地址
            message.setFrom(new InternetAddress(userName));
            //收件人to LIST
            ArrayList<Address> toList = new ArrayList<Address>();
            for (String s:tos) {
                toList.add(new InternetAddress(s));
            }
            //将收件人列表转换为收件人数组
            Address[] addresses = new Address[toList.size()];
            addresses = toList.toArray(addresses);
            //设置to收件人地址
            message.setRecipients(MimeMessage.RecipientType.TO, addresses);
            //设置邮件标题
            message.setSubject(title);
            //设置邮件内容
            message.setContent(content, "text/html;charset=UTF-8");
            //Transport.send(message);
            Transport transport = session.getTransport();
            transport.connect(smtpHost, userName, passWord);
            transport.sendMessage(message, addresses);
            System.out.println("发送邮件成功！");
        } catch (Exception e) {
            System.out.println("发送邮件失败！" + e.getMessage());
            e.printStackTrace();
        }


    }

//    private static String smtpHost = "smtp.exmail.qq.com";
//    private static String userName = "yang.liang@vpclub.cn";
//    private static String passWord = "co06qyrm^w5%o3ya";
//    private static String port = "465";
    private static String smtpHost = "smtp.gmail.com";
    private static String userName = "fintech63@gmail.com";
    private static String passWord = "tsfintech@123";
    private static String port = "465";
    //初始化参数
    public static Session initProperties() {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.host", smtpHost);
        properties.setProperty("mail.smtp.port", port);
        // 使用smtp身份验证
        properties.put("mail.smtp.auth", "true");
        // 使用SSL,企业邮箱必需 start
        // 开启安全协议
        MailSSLSocketFactory mailSSLSocketFactory = null;
        try {
            mailSSLSocketFactory = new MailSSLSocketFactory();
            mailSSLSocketFactory.setTrustAllHosts(true);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        properties.put("mail.smtp.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        properties.put("mail.smtp.socketFactory.port", port);
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, passWord);
            }
        });
        // 使用SSL,企业邮箱必需 end
        // TODO 显示debug信息 正式环境注释掉
//        session.setDebug(true);
        return session;
    }


    private Properties setSmtp(String smtpHost, String smtpPort, String userName, String passWord) {
        //创建邮件配置文件
        Properties maiProperties = new Properties();
        //配置smtp发件服务器
        maiProperties.put("mail.transport.protocol", "smtp");
        //配置smtp服务器
        maiProperties.put("mail.smtp.host", smtpHost);
        //配置smtp服务器端口
        maiProperties.put("mail.smtp.port", smtpPort);
        //配置smtp用户名
        maiProperties.put("mail.user", userName);
        //配置smtp身份验证
        maiProperties.put("mail.smtp.auth", "false");

        return maiProperties;
    }

    private Properties setSmtpQY(String userName, String passWord) {
        //创建邮件配置文件
        Properties maiProperties = new Properties();
        //配置smtp发件服务器  pop.exmail.qq.com
        maiProperties.put("smtp.exmail.qq.com", "smtp");
        //配置smtp服务器
        maiProperties.put("mail.smtp.host", "smtp.exmail.qq.com");
        //配置smtp服务器端口
        maiProperties.put("mail.smtp.port", "465");
        //配置smtp身份验证
        maiProperties.put("mail.smtp.auth", "true");
        maiProperties.put("mail.smtp.ssl.enable", "true");
        maiProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        return maiProperties;
    }


    //smtp 身份验证类
    class Auth extends Authenticator {
        Properties pwdProperties;
        //构造函数

        public Auth(String userName, String passWord) {
            pwdProperties = new Properties();
            try {
                pwdProperties.put(userName, passWord);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

        //必须实现 PasswordAuthentication 方法
        public PasswordAuthentication passwordAuthentication() {
            String userName = getDefaultUserName();
            //当前用户在密码表里
            if (pwdProperties.containsKey(userName)) {
                //取出密码，封装好后返回
                return new PasswordAuthentication(userName, pwdProperties.getProperty(userName).toString());

            } else {
                //如果当前用户不在密码表里就返回Null
                System.out.println("当前用户不存在");
                return null;
            }
        }
    }
}
